package com.audaque.springboot.foshanupload.web.datamongodbdemo.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.audaque.springboot.foshanupload.mongodb.properties.MongodbProperties;
import com.audaque.springboot.foshanupload.web.datamongodbdemo.api.MusicControllerApi;
import com.audaque.springboot.foshanupload.web.datamongodbmodeldemo.model.pojo.Book;
import com.audaque.springboot.foshanupload.web.datamongodbmodeldemo.model.pojo.Chapter;
import com.audaque.springboot.foshanupload.web.datamongodbmodeldemo.model.pojo.MusicDetail;
import com.audaque.springboot.foshanupload.web.datamongodbmodeldemo.model.qo.MusicQo;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.InsertOneResult;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.BsonString;
import org.bson.BsonValue;
import org.bson.codecs.configuration.CodecProvider;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zgb
 * @desc 操作Json，使用Json的api:TDocument
 * @date 2023-07-21 18:48:38
 */
@RestController
@RequestMapping("/musicDetailJsonMongoClient")
public class MusicDetailJsonMongoClientController implements MusicControllerApi {

    @Autowired
    private MongodbProperties mongodbProperties;

    private MongoClient mongoClient;
    private MongoDatabase mongoDatabase;
    private MongoCollection<MusicDetail> collection;

    @PostConstruct
    public void init() {
        //使用automatic(true) 的设置PojoCodecProvider.Builder将编解码器应用于任何类及其属性。
        CodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();

        //fromRegistries()将多个实例合并CodecRegistry为一个实例
        CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), CodecRegistries.fromProviders(pojoCodecProvider));
        mongoClient = MongoClients.create(mongodbProperties.getUrl());
        mongoDatabase = mongoClient.getDatabase(mongodbProperties.getDb()).withCodecRegistry(pojoCodecRegistry);
        //获取集合
        collection = mongoDatabase.getCollection("music_detail", MusicDetail.class);
        if (collection == null) {
            mongoDatabase.createCollection("music_detail");
            System.out.println("集合创建成功");
            //获取集合
            collection = mongoDatabase.getCollection("music_detail", MusicDetail.class);
        }
    }


    @Override
    @PostMapping("/add")
    public String add(@RequestBody MusicDetail musicDetail) {
        //添加id
        musicDetail.setId(new ObjectId().toString());
        Book book = musicDetail.getBook();
        book.setId(new ObjectId().toString());
        Chapter chapter = book.getChapter();
        chapter.setId(new ObjectId().toString());

        InsertOneResult insertOneResult = collection.insertOne(musicDetail);
        BsonValue insertedId = insertOneResult.getInsertedId();
        BsonString bsonString = insertedId.asString();
        String s = bsonString.getValue();
        return s;
    }

    /**
     * 更新：部分更新，但不支持嵌套
     *
     * @param musicDetail
     * @throws Exception
     */
    @Override
    @PutMapping("/edit")
    public void edit(@RequestBody MusicDetail musicDetail) throws Exception {
        String _id = musicDetail.get_id();
        if (StringUtils.isBlank(_id)) {
            throw new Exception("_id不能为null");
        }

        FindIterable<MusicDetail> one = collection.find(Filters.eq("_id", _id));
        MusicDetail first = one.first();
        if (first == null) {
            throw new Exception("根据id查不到该记录");
        }
        MusicDetail byId = first;

        CopyOptions copyOptions = CopyOptions.create();
        copyOptions.setIgnoreNullValue(true);
        copyOptions.setIgnoreProperties("book");
        BeanUtil.copyProperties(musicDetail, byId, copyOptions);

        Book book = musicDetail.getBook();
        Book book1 = byId.getBook();
        copyOptions.setIgnoreProperties("chapter");
        BeanUtil.copyProperties(book, book1, copyOptions);

        Chapter chapter = book.getChapter();
        Chapter chapter1 = book1.getChapter();
        BeanUtil.copyProperties(chapter, chapter1, copyOptions);
        book1.setChapter(chapter1);
        byId.setBook(book1);


        byId.set_id(null);


        collection.replaceOne(Filters.eq("_id", _id), byId);

    }

    @Override
    public void editField(String id, String name) throws Exception {

    }

    @Override
    @PutMapping("/override2json")
    public void override2json(@RequestParam String _id) throws Exception {
        //已经是json

    }

    @Override
    @PutMapping("/override")
    public void override(@RequestBody MusicDetail musicDetail) throws Exception {
        String _id = musicDetail.get_id();

        if (StringUtils.isBlank(_id)) {
            throw new Exception("_id不能为null");
        }


        collection.replaceOne(Filters.eq("_id", _id), musicDetail);
    }

    @Override
    @GetMapping("/get/{id}")
    public MusicDetail get(@PathVariable("id") String _id) {
        List<MusicDetail> records = new ArrayList<MusicDetail>();
        records = collection.find(Filters.eq("_id", _id)).into(records);
        List<MusicDetail> musicDetails = ListUtils.emptyIfNull(records);
        MusicDetail musicDetail = musicDetails.get(0);
        return musicDetail;

    }

    @Override
    public void del(String id) {

    }

    @Override
    public Page<MusicDetail> page(int page, int size, MusicQo musicQo) {
        return null;
    }

    @Override
    public MusicDetail dBRef(String bookId) {
        return null;
    }
}
